<?php

namespace App\Http\Controllers\Application;

use App\Http\Controllers\Controller;
use App\Http\Requests\Application\ColumnrecRequest;
use App\Models\Application\Columnrec;
use App\Models\Application\ColumnRecommendData;
use App\Models\Application\Muticolumn;
use App\Models\Application\Paneltpl;
use App\Models\Entity\Asset\Video\Vasseti;
use App\Models\Entity\Column\Column;
use App\Models\Entity\Column\Collist;
use App\Models\Entity\Column\ColumnFun;
use App\Models\Entity\Column\Data;
use App\Repositories\Application\ColumnrecRepository;
use DB;
use Encore\Admin\Controllers\ModelForm;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Flash;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Route;
use Response;

class ColumnrecController extends Controller
{
    use ModelForm;

    /** @var  ColumnrecRepository */
    private $columnrecRepository;

    public function __construct(ColumnrecRepository $columnrecRepo)
    {
        $this->columnrecRepository = $columnrecRepo;
    }

    /**
     * Display a listing of the Columnrec.
     *
     * @return Response
     */
    public function index(Request $request)
    {
        $muticolumnId = $request->input('muticolumn_id');
        $paneltplId   = $request->input('paneltpl_id');
        if (!empty($muticolumnId) && !empty($paneltplId)) {
            $muticolumn = Muticolumn::find($muticolumnId);

            if (empty($muticolumn)) {
                Flash::error(__('application.muticolumns.not_found'));

                return redirect(route('application.muticolumns.index'));
            }
            // 获取栏目推荐区位信息定义
            $columnrecs = Columnrec::where(['muticolumn_id' => $muticolumnId, 'paneltpl_id' => $paneltplId])->get();
            if (empty($columnrecs->first())) {
                // 获取panel模板信息
                $paneltpl       = Paneltpl::where(['id' => $paneltplId])->first();
                $areas          = json_decode($paneltpl->areas, true);
                $columnrecDatas = [];
                if (!empty($areas)) {
                    foreach ($areas as $key => $area) {
                        $columnrecDatas[$key]['muticolumn_id'] = intval($muticolumnId);
                        $columnrecDatas[$key]['paneltpl_id']   = intval($paneltplId);
                        $columnrecDatas[$key]['area']          = $area;
                        $columnrecDatas[$key]['created_at']    = date('Y-m-d H:i:s', time());
                    }
                }
                $result = DB::table('columnrecs')->insert($columnrecDatas);
                if (empty($result)) {
                    Flash::error(__('application.muticolumns.not_found'));

                    return redirect(route('application.muticolumns.index'));
                }
            }
        }

        return Admin::content(function (Content $content) use ($request) {

            $content->header(__('application.columnrecs.index_header'));
            $content->description(__('application.columnrecs.index_description'));

            $content->body($this->grid($request));
            $content->row(view('application.columnrecs.index'));

        });
    }

    /**
     * Show the form for creating a new Columnrec.
     *
     * @return Response
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header(__('application.columnrecs.create_header'));
            $content->description(__('application.columnrecs.create_description'));

            $content->body($this->form());

        });
    }

    /**
     * Store a newly created Columnrec in storage.
     *
     * @param ColumnrecRequest $request
     *
     * @return Response
     */
    public function store(ColumnrecRequest $request)
    {
        $input = $request->all();

        $columnrec = $this->columnrecRepository->create($input);
        if ($columnrec) {
            if (is_array($request->get('columnrecommenddatas'))) {
                $columnrec->columnrecommenddatas()->sync(array_filter($request->get('columnrecommenddatas')));
            }
        }
        Flash::success(__('application.columnrecs.saved_success'));

        return Input::get('_previous_') ? redirect(Input::get('_previous_')) : redirect(route('application.columnrecs.index'));

    }

    /**
     * Display the specified Columnrec.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function show($id)
    {
        $columnrec = $this->columnrecRepository->findWithoutFail($id);

        if (empty($columnrec)) {
            Flash::error(__('application.columnrecs.not_found'));

            return redirect(route('application.columnrecs.index'));
        }

        return view('application.columnrecs.show')->with('columnrec', $columnrec);

    }

    /**
     * Show the form for editing the specified Columnrec.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function edit($id)
    {

        return Admin::content(function (Content $content) use ($id) {

            $content->header(__('application.columnrecs.edit_header'));
            $content->description(__('application.columnrecs.edit_description'));

            $content->body($this->form()->edit($id));
        });
    }

    /**
     * Update the specified Columnrec in storage.
     *
     * @param  int              $id
     * @param ColumnrecRequest $request
     *
     * @return Response
     */
    public function update($id, ColumnrecRequest $request)
    {
        $columnrec = $this->columnrecRepository->findWithoutFail($id);

        if (empty($columnrec)) {
            Flash::error(__('application.columnrecs.not_found'));

            return redirect(route('application.columnrecs.index'));
        }
        $input = $request->all();

        $columnrec = $this->columnrecRepository->update($input, $id);
        if ($columnrec) {
            if (is_array($request->get('columnrecommenddatas'))) {
                $columnrec->columnrecommenddatas()->sync(array_filter($request->get('columnrecommenddatas')));
            }
        }
        Flash::success(__('application.columnrecs.updated_success'));

        return Input::get('_previous_') ? redirect(Input::get('_previous_')) : redirect(route('application.columnrecs.index'));
    }

    /**
     * Remove the specified Columnrec from storage.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function destroy($id)
    {
        // 根据 `,` 判断传递过来的是单个id还是多个id
        if (substr_count($id, ',') >= 1) {
            $id = explode(",", $id);
        }

        // 如果是数组则进行批量删除
        if (is_array($id)) {
            if ($flag = $this->columnrecRepository->batchDelete('id', $id)) {

                return response()->json(['message' => __('application.columnrecs.deleted_success'), 'status' => $flag]);
            } else {
                return response()->json(['message' => __('base.deleted.error'), 'status' => $flag]);
            }
        }

        $columnrec = $this->columnrecRepository->findWithoutFail($id);

        if (empty($columnrec)) {
            Flash::error(__('application.columnrecs.not_found'));

            return redirect(route('application.columnrecs.index'));
        }

        if ($flag = $this->columnrecRepository->delete($id)) {

            return response()->json(['message' => __('application.columnrecs.deleted_success'), 'status' => $flag]);
        } else {
            return response()->json(['message' => __('base.deleted.error'), 'status' => $flag]);
        }
    }

    /**
     * [form description]
     * @return {[type]} [description]
     */
    protected function form()
    {
        return Admin::form(Columnrec::class, function (Form $form) {

            $form->display('id', 'ID');
            $muticolumns = Muticolumn::pluck('name', 'id');
            $form->select('muticolumn_id', '选择栏目')->options($muticolumns);
            $paneltpls = Paneltpl::pluck('name', 'id');
            $form->select('paneltpl_id', 'panel模板')->options($paneltpls);
            $form->text('area', '区位编号');
            $columnRecommendDatas = ColumnRecommendData::pluck('name', 'id');
            $form->multipleSelect('columnrecommenddatas', '选择推荐数据')->options($columnRecommendDatas);

            // $form->display('created_at', __('base.created_at'));
            // $form->display('updated_at', __('base.updated_at'));

        });
    }

    /**
     * [grid description]
     * @return {[type]} [description]
     */
    protected function grid(Request $request)
    {

        return Admin::grid(Columnrec::class, function (Grid $grid) use ($request) {
            // 考虑是否需要scope和排序
            // $grid->model()->orderBy('listorder', 'asc');
            if (!empty($request->get('muticolumn_id'))) {
                $muticolumnId = $request->get('muticolumn_id');
                $paneltplId   = $request->get('paneltpl_id');
                $grid->model()->where(['muticolumn_id' => $muticolumnId, 'paneltpl_id' => $paneltplId]);
            } else {
                $grid->model();

            }

            // // 添加按钮
            // if (!\Gate::check('application.columnrecs.create')) {
            //     $grid->disableCreation();
            // }

            // // 编辑和删除按钮
            // $grid->actions(function ($actions) {
            //     // 编辑按钮
            //     if (!\Gate::check('application.columnrecs.edit')) {
            //         $actions->disableEdit();
            //     }
            //     // 删除按钮
            //     if (!\Gate::check('application.columnrecs.destroy')) {
            //         $actions->disableDelete();
            //     }
            // });

            // // 导出按钮
            // if (!\Gate::check('application.columnrecs.export')) {
            //     $grid->disableExport();
            // }

            // // 批量操作
            // $grid->tools(function ($tools) {
            //     $tools->batch(function ($batch) {
            //         // 批量删除按钮
            //         if (!\Gate::check('application.columnrecs.batch_destroy')) {
            //             $batch->disableDelete();
            //         }
            //     });
            // });

            // 添加按钮
            // if (Admin::user()->cannot('application.columnrecs.create')) {
            $grid->disableCreation();
            // }

            // 编辑和删除按钮
            $grid->actions(function ($actions) {
                $id = $actions->getKey();
                // 编辑按钮
                if (Admin::user()->cannot('application.columnrecs.edit')) {
                    $actions->disableEdit();
                }
                // 删除按钮
                if (Admin::user()->cannot('application.columnrecs.destroy')) {
                    $actions->disableDelete();
                }
                //添加推荐数据
                $url = route('application.columnrecs.add_recommend_data', ['columnrec_id' => $id]);
                $actions->append('<a href="' . $url . '" data-toggle="modal"  data-target="#add-coloumnrec-modal" title="添加推荐数据">推荐数据编辑</a>');

            });

            // 导出按钮
            if (Admin::user()->cannot('application.columnrecs.export')) {
                $grid->disableExport();
            }

            // 批量操作
            $grid->tools(function ($tools) {
                $tools->batch(function ($batch) {
                    // 批量删除按钮
                    if (Admin::user()->cannot('application.columnrecs.batch_destroy')) {
                        $batch->disableDelete();
                    }
                });
                $tools->append('<a href="javascript:void(0)" onclick="history.go(-1)" class="btn btn-default btn-sm" style="margin-right: 0px"> <i class="fa fa-arrow-left"></i>返回</a>');
            });

            $grid->column('id', 'ID')->sortable();
            $grid->column('muticolumn.name', '栏目名称')->sortable();
            $grid->column('paneltpl.name', 'panel模板')->sortable();
            $grid->column('area', '区位编号')->sortable();
            $grid->columnRecommendDatas('推荐数据')->pluck('title')
            // ->implode(',')
                ->display(function ($val) {
                    // $returnData = [];
                    // foreach ($val as $key => $value) {
                    //     $returnData[] = '<span class="badge bg-green">'.$value.'</span>';
                    // }
                    // $val = implode(' ', $returnData);
                    $url  = route('application.column_recommend_datas.index', ['columnrec_id' => $this->id]);
                    $data = "<a target='_blank' href=" . $url . ">" . count($val) . "条数据</a>";
                    return $data;
                });

            /**
             * 过滤处理
             */
            $grid->filter(function ($filter) {
                // // 禁用id查询框
                // $filter->disableIdFilter();
                $filter->like('name', '名称');

            });
        });
    }

    /**
     * 加载公共区域视图
     * @param Request $request [description]
     */
    public function addRecommendDatas(Request $request)
    {
        // Admin::script('addPublicRecommendData();');

        $columnrecId = $request->input('columnrec_id');

        $columnrec = $this->columnrecRepository->findWithoutFail($columnrecId);

        if (empty($columnrec)) {
            Flash::error(__('application.columnrecs.not_found'));

            return redirect(route('application.columnrecs.index'));
        }
        $datas                 = [];
        $data                  = Data::get(['title', 'id'])->toArray();
        $datas['datas']        = $data;
        $datas['columnrec_id'] = $columnrecId;
        return view('application.columnrecs.create', $datas);
    }

    /**
     * datatable返回数据
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function getDataByModel(Request $request)
    {
        // 搜索框的值
        $search_value = $request->input('search_value');
        // 获取数据类型
        $dataType = $request->input('data_type');
        // 获取栏目推荐区位ID
        $columnrecId = $request->input('columnrec_id');
        // 获取此推荐位所有已选择的推荐数据ID
        $columnrecRecDatas      = DB::table('columnrec_column_recommend_datas')->where(['columnrec_id' => $columnrecId])->pluck('column_recommend_data_id')->toArray();
        $columnRecommendDataIds = ColumnRecommendData::whereIn('id', $columnrecRecDatas)->where(['data_id' => $dataType])->pluck('resource_data_id')->toArray();
        // 获取此类型的数据ID
        $data      = Data::where(['id' => $dataType])->first();
        $relation  = [];
        $whereData = [];
        if ($data) {
            switch ($data->name) {
                case 'collist':
                    $model = new Collist();
                    break;
                case 'column0':
                    $model = new Muticolumn();
                    break;
                case 'column1':
                    $model = new Muticolumn();
                    break;
                case 'column2':
                    $model = new Muticolumn();
                    break;
                case 'vasset':
                    $model    = new Vasseti();
                    $relation = ['vcat', 'actors', 'directors', 'vareas', 'vlangs', 'vyears', 'vcattags'];
                    break;
                case 'aasset':
                    $model    = new Vasseti();
                    $relation = ['vcat', 'actors', 'directors', 'vareas', 'vlangs', 'vyears', 'vcattags'];
                    break;
                case 'iasset':
                    $model    = new Vasseti();
                    $relation = ['vcat', 'actors', 'directors', 'vareas', 'vlangs', 'vyears', 'vcattags'];
                    break;
                case 'column_fun':
                    $model = new ColumnFun();
                    break;
                default:
                    $model    = new Vasseti();
                    $relation = ['vcat', 'actors', 'directors', 'vareas', 'vlangs', 'vyears', 'vcattags'];
                    break;
            }
        } else {
            $model = new Vasseti();
        }

        $model = (new \ReflectionClass($model))->getName();

        $data         = [];
        $data['draw'] = $request->get('draw');
        $start        = $request->get('start') ?: 0;
        $length       = $request->get('length') ?: 10;
        $order        = $request->get('order');
        $columns      = $request->get('columns');
        $search       = $request->get('search');
        if ($order) {
            $orderColumData = $columns[$order[0]['column']]['data'];
        }

        // 排序字段
        $ord = '';
        if (!empty($orderColumData)) {
            $ord = $orderColumData . ' ' . $order[0]['dir'];
        } else {
            $ord = 'id asc';
        }
        $data['recordsTotal']    = $model::where($whereData)->whereNotIn('id', $columnRecommendDataIds)->count();
        $data['recordsFiltered'] = $model::where($whereData)->whereNotIn('id', $columnRecommendDataIds)->count();
        $data['data']            = $model::with($relation)
            ->whereNotIn('id', $columnRecommendDataIds)
            ->where($whereData)
            ->skip($start)->take($length)
            ->orderByRaw($ord)
            ->get();
        return response()->json($data);
    }

    /**
     * 推荐数据包
     * @param  tag_contentRequest $request [description]
     * @return [type]                      [description]
     */
    public function recommendStore(Request $request)
    {
        // 获取传递过来是哪个栏目推荐
        $columnrecId = $request->input('columnrec_id');
        if (empty($columnrecId)) {
            return response()->json(['content' => '推荐位ID不能为空', 'status' => false]);
        }
        // 获取数据类型
        $dataType = $request->input('data_type');
        if (empty($dataType)) {
            return response()->json(['content' => '数据类型ID不能为空', 'status' => false]);
        }
        // 获取所有传递来的数据ID
        $dataId = $request->input('data_id');
        if (!is_array($dataId)) {
            return response()->json(['content' => '数据为空,请选择数据', 'status' => false]);
        }

        $data = Data::where(['id' => $dataType])->first();
        if (empty($data)) {
            return response()->json(['content' => '无此数据类型', 'status' => false]);

        }
        $datas = [];

        $colRecDatas = [];
        switch ($data->name) {
            case 'collist':
                   DB::beginTransaction();
                try {
                    $columnRecommendDataId = 0;
                    foreach ($dataId as $key => $value) {
                        // 去推荐数据表中看是否已有此数据
                        $columnRecommendData = ColumnRecommendData::where(['data_id' => $dataType, 'resource_data_id' => $value])->first();
                        if (empty($columnRecommendData)) {
                            $collist = Collist::where(['id' => $value])->first();
                            if ($collist) {
                                $datas['name']             = $collist->name;
                                $datas['title']            = $collist->title;
                                $datas['data_id']          = $dataType;
                                $datas['resource_data_id'] = $value;
                                $datas['order']            = 0;
                                $columnRecommendDataId     = DB::table('column_recommend_datas')->insertGetId($datas);
                            }
                        } else {
                            $columnRecommendDataId = $columnRecommendData->id;
                        }
                        // 判断当前数据是否已存在
                        if ($this->isExistColumnRecData($columnrecId, $columnRecommendDataId)) {
                            $colRecDatas[$key]['columnrec_id']             = $columnrecId;
                            $colRecDatas[$key]['column_recommend_data_id'] = $columnRecommendDataId;
                        }
                    }
                    DB::table('columnrec_column_recommend_datas')->insert($colRecDatas);
                    DB::commit();
                    return response()->json(['content' => '添加成功！', 'status' => true]);
                } catch (Exception $e) {
                    DB::rollback();
                }
                break;
            case 'column0':
                DB::beginTransaction();
                try {
                    $columnRecommendDataId = 0;
                    foreach ($dataId as $key => $value) {
                        // 去推荐数据表中看是否已有此数据
                        $columnRecommendData = ColumnRecommendData::where(['data_id' => $dataType, 'resource_data_id' => $value])->first();
                        if (empty($columnRecommendData)) {
                            $column = Muticolumn::where(['id' => $value])->first();
                            if ($column) {
                                $datas['name']             = $column->name;
                                $datas['title']            = $column->name;
                                $datas['data_id']          = $dataType;
                                $datas['resource_data_id'] = $value;
                                $datas['order']            = 0;
                                $columnRecommendDataId     = DB::table('column_recommend_datas')->insertGetId($datas);
                            }
                        } else {
                            $columnRecommendDataId = $columnRecommendData->id;
                        }
                        // 判断当前数据是否已存在
                        if ($this->isExistColumnRecData($columnrecId, $columnRecommendDataId)) {
                            $colRecDatas[$key]['columnrec_id']             = $columnrecId;
                            $colRecDatas[$key]['column_recommend_data_id'] = $columnRecommendDataId;
                        }
                    }
                    DB::table('columnrec_column_recommend_datas')->insert($colRecDatas);
                    DB::commit();
                    return response()->json(['content' => '添加成功！', 'status' => true]);
                } catch (Exception $e) {
                    DB::rollback();
                }
                break;
            case 'column1':
                DB::beginTransaction();
                try {
                    foreach ($dataId as $key => $value) {
                        // 去推荐数据表中看是否已有此数据
                        $columnRecommendData = ColumnRecommendData::where(['data_id' => $dataType, 'resource_data_id' => $value])->first();
                        if (empty($columnRecommendData)) {
                            $subcolumn = Muticolumn::where(['id' => $value])->first();
                            if ($subcolumn) {

                                $datas['name']             = $subcolumn->name;
                                $datas['title']            = $subcolumn->name;
                                $datas['data_id']          = $dataType;
                                $datas['resource_data_id'] = $value;
                                $datas['order']            = 0;
                                $columnRecommendDataId     = DB::table('column_recommend_datas')->insertGetId($datas);
                            }
                        } else {
                            $columnRecommendDataId = $columnRecommendData->id;
                        }
                        // 判断当前数据是否已存在
                        if ($this->isExistColumnRecData($columnrecId, $columnRecommendDataId)) {
                            $colRecDatas[$key]['columnrec_id']             = $columnrecId;
                            $colRecDatas[$key]['column_recommend_data_id'] = $columnRecommendDataId;
                        }
                    }
                    DB::table('columnrec_column_recommend_datas')->insert($colRecDatas);
                    DB::commit();
                    return response()->json(['content' => '添加成功！', 'status' => true]);
                } catch (Exception $e) {
                    DB::rollback();
                }
                break;
            case 'vasset':
                DB::beginTransaction();
                try {
                    foreach ($dataId as $key => $value) {
                        // 去推荐数据表中看是否已有此数据
                        $columnRecommendData = ColumnRecommendData::where(['data_id' => $dataType, 'resource_data_id' => $value])->first();
                        if (empty($columnRecommendData)) {
                            $vasseti = Vasseti::where(['id' => $value])->first();

                            if ($vasseti) {

                                $datas['name']             = $vasseti->name;
                                $datas['title']            = $vasseti->name;
                                $datas['data_id']          = $dataType;
                                $datas['resource_data_id'] = $value;
                                $datas['order']            = 0;
                                $columnRecommendDataId     = DB::table('column_recommend_datas')->insertGetId($datas);
                            }
                        } else {
                            $columnRecommendDataId = $columnRecommendData->id;
                        }
                        // 判断当前数据是否已存在
                        if ($this->isExistColumnRecData($columnrecId, $columnRecommendDataId)) {
                            $colRecDatas[$key]['columnrec_id']             = $columnrecId;
                            $colRecDatas[$key]['column_recommend_data_id'] = $columnRecommendDataId;
                        }
                    }
                    DB::table('columnrec_column_recommend_datas')->insert($colRecDatas);
                    DB::commit();
                    return response()->json(['content' => '添加成功！', 'status' => true]);
                } catch (Exception $e) {
                    DB::rollback();
                }
                break;
            case 'aasset':
                DB::beginTransaction();
                try {
                    foreach ($dataId as $key => $value) {
                        // 去推荐数据表中看是否已有此数据
                        $columnRecommendData = ColumnRecommendData::where(['data_id' => $dataType, 'resource_data_id' => $value])->first();
                        if (empty($columnRecommendData)) {
                            $vasseti = Vasseti::where(['id' => $value])->first();
                            if ($vasseti) {

                                $datas['name']             = $vasseti->name;
                                $datas['title']            = $vasseti->name;
                                $datas['data_id']          = $dataType;
                                $datas['resource_data_id'] = $value;
                                $datas['order']            = 0;
                                $columnRecommendDataId     = DB::table('column_recommend_datas')->insertGetId($datas);
                            }
                        } else {
                            $columnRecommendDataId = $columnRecommendData->id;
                        }
                        // 判断当前数据是否已存在
                        if ($this->isExistColumnRecData($columnrecId, $columnRecommendDataId)) {
                            $colRecDatas[$key]['columnrec_id']             = $columnrecId;
                            $colRecDatas[$key]['column_recommend_data_id'] = $columnRecommendDataId;
                        }
                    }
                    DB::table('columnrec_column_recommend_datas')->insert($colRecDatas);
                    DB::commit();
                    return response()->json(['content' => '添加成功！', 'status' => true]);
                } catch (Exception $e) {
                    DB::rollback();
                }
                break;
            case 'iasset':
                DB::beginTransaction();
                try {
                    foreach ($dataId as $key => $value) {
                        // 去推荐数据表中看是否已有此数据
                        $columnRecommendData = ColumnRecommendData::where(['data_id' => $dataType, 'resource_data_id' => $value])->first();
                        if (empty($columnRecommendData)) {
                            $vasseti = Vasseti::where(['id' => $value])->first();
                            if ($vasseti) {

                                $datas['name']             = $vasseti->name;
                                $datas['title']            = $vasseti->name;
                                $datas['data_id']          = $dataType;
                                $datas['resource_data_id'] = $value;
                                $datas['order']            = 0;
                                $columnRecommendDataId     = DB::table('column_recommend_datas')->insertGetId($datas);
                            }
                        } else {
                            $columnRecommendDataId = $columnRecommendData->id;
                        }
                        // 判断当前数据是否已存在
                        if ($this->isExistColumnRecData($columnrecId, $columnRecommendDataId)) {
                            $colRecDatas[$key]['columnrec_id']             = $columnrecId;
                            $colRecDatas[$key]['column_recommend_data_id'] = $columnRecommendDataId;
                        }
                    }
                    DB::table('columnrec_column_recommend_datas')->insert($colRecDatas);
                    DB::commit();
                    return response()->json(['content' => '添加成功！', 'status' => true]);
                } catch (Exception $e) {
                    DB::rollback();
                }
                break;
            case 'column_fun':
                DB::beginTransaction();
                try {
                    foreach ($dataId as $key => $value) {
                        // 去推荐数据表中看是否已有此数据
                        $columnRecommendData = ColumnRecommendData::where(['data_id' => $dataType, 'resource_data_id' => $value])->first();
                        if (empty($columnRecommendData)) {
                            $vasseti = ColumnFun::where(['id' => $value])->first();
                            if ($vasseti) {
                                $datas['name']             = $vasseti->name;
                                $datas['title']            = $vasseti->name;
                                $datas['data_id']          = $dataType;
                                $datas['resource_data_id'] = $value;
                                $datas['order']            = 0;
                                $columnRecommendDataId     = DB::table('column_recommend_datas')->insertGetId($datas);
                            }
                        } else {
                            $columnRecommendDataId = $columnRecommendData->id;
                        }
                        // 判断当前数据是否已存在
                        if ($this->isExistColumnRecData($columnrecId, $columnRecommendDataId)) {
                            $colRecDatas[$key]['columnrec_id']             = $columnrecId;
                            $colRecDatas[$key]['column_recommend_data_id'] = $columnRecommendDataId;
                        }
                    }
                    DB::table('columnrec_column_recommend_datas')->insert($colRecDatas);
                    DB::commit();
                    return response()->json(['content' => '添加成功！', 'status' => true]);
                } catch (Exception $e) {
                    DB::rollback();
                }
                break;
            default:
                return response()->json(['content' => '添加成功！', 'status' => true]);
                break;
        }
    }

    /**
     * 判断推荐此数据是否已存在
     * @param  [type]  $columnrecId           [description]
     * @param  [type]  $columnRecommendDataId [description]
     * @return boolean                        [description]
     */
    public function isExistColumnRecData($columnrecId, $columnRecommendDataId)
    {
        $flag          = true;
        $columnRecData = DB::table('columnrec_column_recommend_datas')
            ->where(['columnrec_id' => $columnrecId, 'column_recommend_data_id' => $columnRecommendDataId])
            ->first();
        if (!empty($columnRecData)) {
            $flag = false;
        }
        return $flag;
    }
}
